// const { unlink, watch } = require("node:fs/promises");

// (async function (path) {
//   try {
//     await unlink(path);
//     console.log(`successfully deleted ${path}`);
//   } catch (error) {
//     console.error("there was an error:", error.message);
//   }
// })("./hello");
// unlink("./hello", (err) => {
//   if (err) throw err;
//   console.log("successfully deleted /tmp/hello");
// });

// watchFile("./watchfile.md", (curr, prev) => {
//   console.log(`event type: ${eventType}, filename: ${filename}`);
// });

// // 监听watchdir目录
// watch("./watchdir", { recursive: true }, (eventType, filename) => {
//   console.log(`event type: ${eventType}, filename: ${filename}`);
// });
// const fs = require("fs");
// const path = require("path");
// console.log(path.dirname(__filename));
// // Example when handled through fs.watch() listener
// watch("./tmp", { encoding: "utf-8" }, (eventType, filename) => {
//   console.log(`event type: ${eventType}, filename: ${filename}`);
//   if (filename) {
//     console.log(filename);
//     // Prints: <Buffer ...>
//   }
// });

const fs = require("fs");
const path = require("path");

// 要监听的文件路径
const filePath = path.join(__dirname, "./tmp");

// 监听文件变化
const watcher = fs.watch(filePath, (eventType, filename) => {
  if (filename) {
    console.log(`文件 ${filename} 发生了 ${eventType} 变化`);

    // 读取变化后的内容
    fs.readFile(filePath, "utf8", (err, data) => {
      if (err) throw err;
      console.log("文件内容:", data);
    });
  }
});

// 处理错误
watcher.on("error", (err) => {
  console.error("监听错误:", err);
});

// 当需要停止监听时
// watcher.close();
